package cn.icesun.comall.cybershoptest.module.order.controller;

import cn.icesun.comall.cybershoptest.module.order.entity.Order;
import cn.icesun.comall.cybershoptest.module.order.service.IOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/base/test/orders")
@Api(value = "订单管理", tags = "订单管理")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @ApiOperation("新增订单")
    @PostMapping("/random")
    public Order saveRandom(HttpServletResponse response){
        Order order = new Order()
                .setOrderNo(UUID.randomUUID().toString().replace("-", ""))
                .setOrderAmount(
                        new BigDecimal(new Random().nextInt(1000000))
                                .divide(new BigDecimal("100"), 2, RoundingMode.UP))
                .setUserId(0)
                .setReceiverMobile(String.format("1894010%04d", new Random().nextInt(9999)))
                .setReceiverAddress("未知");
        if (orderService.save(order)){
            response.setStatus(HttpServletResponse.SC_CREATED);
            return order;
        }
        else {
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

    }
}
